package com.newsplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newsplatform.common.Constants;
import com.newsplatform.dto.NewsRequest;
import com.newsplatform.entity.News;
import com.newsplatform.entity.User;
import com.newsplatform.mapper.NewsMapper;
import com.newsplatform.service.NewsService;
import com.newsplatform.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * 新闻服务实现类
 * 
 * @author Logan.Li
 */
@Service
@RequiredArgsConstructor
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements NewsService {
    
    private final UserService userService;
    
    @Override
    public IPage<News> getNewsPage(Integer page, Integer size, Integer status, Long categoryId, String keyword) {
        Page<News> pageParam = new Page<>(page, size);
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        if (categoryId != null) {
            queryWrapper.eq("category_id", categoryId);
        }
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                .like("title", keyword)
                .or()
                .like("summary", keyword)
                .or()
                .like("content", keyword)
            );
        }
        
        queryWrapper.orderByDesc("is_top", "publish_time");
        
        return page(pageParam, queryWrapper);
    }
    
    @Override
    public News createNews(NewsRequest request, String username) {
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        News news = new News();
        news.setTitle(request.getTitle());
        news.setSummary(request.getSummary());
        news.setContent(request.getContent());
        news.setCoverImage(request.getCoverImage());
        news.setCategoryId(request.getCategoryId());
        news.setAuthorId(user.getId());
        news.setStatus(request.getStatus() != null ? request.getStatus() : Constants.NEWS_STATUS_DRAFT);
        news.setViewCount(0);
        news.setLikeCount(0);
        news.setIsTop(request.getIsTop() != null ? request.getIsTop() : 0);
        news.setDesc(request.getDesc());
        
        if (news.getStatus().equals(Constants.NEWS_STATUS_PUBLISHED)) {
            news.setPublishTime(LocalDateTime.now());
        }
        
        save(news);
        return news;
    }
    
    @Override
    public News updateNews(Long id, NewsRequest request, String username) {
        News news = getById(id);
        if (news == null) {
            throw new RuntimeException("新闻不存在");
        }
        
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查权限：只有作者或管理员可以编辑
        if (!news.getAuthorId().equals(user.getId()) && !Constants.ROLE_ADMIN.equals(user.getRole())) {
            throw new RuntimeException("没有权限编辑此新闻");
        }
        
        news.setTitle(request.getTitle());
        news.setSummary(request.getSummary());
        news.setContent(request.getContent());
        news.setCoverImage(request.getCoverImage());
        news.setCategoryId(request.getCategoryId());
        if (request.getStatus() != null) {
            news.setStatus(request.getStatus());
        }
        if (request.getIsTop() != null) {
            news.setIsTop(request.getIsTop());
        }
        news.setDesc(request.getDesc());
        
        updateById(news);
        return news;
    }
    
    @Override
    public void publishNews(Long id, String username) {
        News news = getById(id);
        if (news == null) {
            throw new RuntimeException("新闻不存在");
        }
        
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查权限
        if (!news.getAuthorId().equals(user.getId()) && !Constants.ROLE_ADMIN.equals(user.getRole())) {
            throw new RuntimeException("没有权限发布此新闻");
        }
        
        news.setStatus(Constants.NEWS_STATUS_PUBLISHED);
        news.setPublishTime(LocalDateTime.now());
        updateById(news);
    }
    
    @Override
    public void incrementViewCount(Long id) {
        baseMapper.incrementViewCount(id);
    }
    
    @Override
    public void likeNews(Long id) {
        baseMapper.incrementLikeCount(id);
    }
    
    @Override
    public IPage<News> getHotNews(Integer page, Integer size) {
        Page<News> pageParam = new Page<>(page, size);
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.NEWS_STATUS_PUBLISHED);
        queryWrapper.orderByDesc("view_count", "like_count");
        
        return page(pageParam, queryWrapper);
    }
    
    @Override
    public void archiveNews(Long id, String username) {
        News news = getById(id);
        if (news == null) {
            throw new RuntimeException("新闻不存在");
        }
        
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查权限
        if (!news.getAuthorId().equals(user.getId()) && !Constants.ROLE_ADMIN.equals(user.getRole())) {
            throw new RuntimeException("没有权限归档此新闻");
        }
        
        news.setStatus(Constants.NEWS_STATUS_ARCHIVED);
        updateById(news);
    }
    
    @Override
    public void toggleTopNews(Long id, Boolean isTop, String username) {
        News news = getById(id);
        if (news == null) {
            throw new RuntimeException("新闻不存在");
        }
        
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查权限：只有管理员可以置顶
        if (!Constants.ROLE_ADMIN.equals(user.getRole())) {
            throw new RuntimeException("没有权限执行此操作");
        }
        
        news.setIsTop(isTop ? 1 : 0);
        updateById(news);
    }
    
    @Override
    public void batchDeleteNews(java.util.List<Long> ids, String username) {
        User user = userService.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查权限：只有管理员可以批量删除
        if (!Constants.ROLE_ADMIN.equals(user.getRole())) {
            throw new RuntimeException("没有权限执行此操作");
        }
        
        removeByIds(ids);
    }
    
    @Override
    public IPage<News> getLatestNews(Integer page, Integer size) {
        Page<News> pageParam = new Page<>(page, size);
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.NEWS_STATUS_PUBLISHED);
        queryWrapper.orderByDesc("publish_time", "gmt_create");
        
        return page(pageParam, queryWrapper);
    }
    
    @Override
    public IPage<News> getRecommendedNews(Integer page, Integer size) {
        Page<News> pageParam = new Page<>(page, size);
        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", Constants.NEWS_STATUS_PUBLISHED);
        // 推荐算法：综合考虑置顶、浏览量、点赞数和发布时间
        queryWrapper.orderByDesc("is_top", "view_count + like_count * 2", "publish_time");
        
        return page(pageParam, queryWrapper);
    }
    
}
